# -*- coding: utf-8 -*-

import logging

from model import business_lock_api as db_business_lock

LOG = logging.getLogger()


class DBMultiLock(object):
    def __init__(self, params, description, timeout):
        self.params = params            # 对应DB中真正的unique key
        self.description = description  # string 描述性信息
        self.timeout = timeout

    def __enter__(self):
        self.acquire()
        LOG.info('model unique lock enter success')

    def __exit__(self, exc_type, exc_value, traceback):
        LOG.info('exe_type: %s' % exc_type)
        LOG.info('exc_value: %s' % exc_value)
        LOG.info('traceback: %s' % traceback)
        self.release()
        LOG.info('model unique lock exit success')

    def acquire(self):
        lock_data = {
            'params': self.params,
            'description': self.description,
            'timeout': self.timeout,
        }
        # 加锁。如果加锁失败，则直接异常退出
        db_business_lock.get_locks(**lock_data)
        LOG.info('acquire model locks success params {} description {}'.format(self.params, self.description))

    def release(self):
        LOG.info('release model params {} description {}'.format(self.params, self.description))
        if self.params:
            db_business_lock.delete_locks(params=self.params)
            LOG.info('release model locks success')
